<template>
  <el-row>

    <el-row style="margin: 20px 0px 10px 0px">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/bashbord' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/ecs-list' }">主机管理</el-breadcrumb-item>
        <el-breadcrumb-item>概览</el-breadcrumb-item>
      </el-breadcrumb>
    </el-row>

    <el-row>
      <el-tabs v-model="defaultActivityName" @tab-click="handleClick">

        <el-tab-pane label="概览" name="first">
          <div style="width:97.5%;display:flex;flex-direction:row;align-items:center;justify-content:flex-end;">
            <el-select size="small"  style="width:130px;margin-right:10px;" v-model="time" placeholder="刷新时间"  @change="selectTime">
              <el-option v-for="item in selectTimeData" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>

            <el-select size="small"  style="width:130px;" multiple v-model="chart" placeholder="选择图表"  @change="selectChart">
              <el-option v-for="item in selectChartData" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </div>

          <div style="width:100%;display:flex;flex-direction:row;justify-content:space-evenly">

            <div style="width:25%;display:flex;flex-direction:column;">

              <el-card style="width:95%;margin:10px;" v-loading="loadingInformation">
                <el-row>
                  <el-col :span="1"><div style="width: 4px;height: 17px;background-color: #409EFF;"></div></el-col>
                  <el-col :span="5" style="line-height: 17px">基本信息</el-col>
                </el-row>
                <el-row class="row">
                  <el-col :span="15" class="color">{{essentialInformation.name}}</el-col>
                  <el-col :span="5">
                    <el-select size="mini"  style="width:100px;" clearable v-model="value" placeholder="更多"  @change="operation">
                      <el-option
                        v-for="item in select"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-col>
                </el-row>
                <el-row class="row">
                  <el-col :span="15" class="color">管理IP</el-col>
                  <el-col :span="5" class="font">{{essentialInformation.ip}}</el-col>
                </el-row>
                <el-row class="row">
                  <el-col :span="15" class="color">业务IP</el-col>
                  <el-col :span="5" class="font">{{essentialInformation.serviceIp}}</el-col>
                </el-row>
                <el-row class="row">
                  <el-col :span="15" class="color">内存</el-col>
                  <el-col :span="5" class="font">{{essentialInformation.memory}}</el-col>
                </el-row>
                <el-row class="row">
                  <el-col :span="15" class="color">CPU</el-col>
                  <el-col :span="5" class="font">{{essentialInformation.cpu}}</el-col>
                </el-row>
                <el-row class="row">
                  <el-col :span="15" class="color">实例状态</el-col>
                  <el-col :span="5" class="font">
                    <div v-if="essentialInformation.state == 'ACTIVE'">
                      <div style="width: 8px;height: 8px;background-color: #5EDD86;border-radius: 50%;display:inline-block"></div>
                      <div style="display:inline-block">{{runStates[0].label}}</div>
                    </div>
                    <div v-else>
                      <div style="width: 8px;height: 8px;background-color: red;border-radius: 50%;display:inline-block"></div>
                      <div style="display:inline-block">{{runStates[2].label}}</div>
                    </div>
                  </el-col>
                </el-row>
                <el-row class="row">
                  <el-col :span="15" class="color">JAVA版本</el-col>
                  <el-col :span="5" class="font">{{essentialInformation.java}}</el-col>
                </el-row>
                <el-row class="row">
                  <el-col :span="15" class="color">Python版本</el-col>
                  <el-col :span="5" class="font">{{essentialInformation.py}}</el-col>
                </el-row>
                <el-row class="row">
                  <el-col :span="15" class="color">sshpass版本</el-col>
                  <el-col :span="5" class="font">{{essentialInformation.ssh}}</el-col>
                </el-row>
              </el-card>

              <el-card style="width:95%;margin:10px;" v-loading="loadingInformation">
                <el-row>
                  <el-col :span="1">
                    <div style="width: 4px;height: 17px;background-color: #409EFF;"></div>
                  </el-col>
                  <el-col :span="3" style="line-height: 17px">磁盘</el-col>
                </el-row>
                <el-row>
                  <el-table height="210px" :data="essentialInformation.disks" style="margin-top:10px" :header-cell-style="{'background-color':'#F5F5F5','color':'#333333 ','font-size':'12px','text-align':'center','padding':'0','height':'10px','line-height':'3px'}">
                    <el-table-column align="center" :show-overflow-tooltip="true" prop="diskName" label="磁盘" width="75"></el-table-column>
                    <el-table-column align="center" :show-overflow-tooltip="true" prop="diskMount" label="挂载点" width="75"></el-table-column>
                    <el-table-column align="center" :show-overflow-tooltip="true" label="已使用" width="200">
                      <template slot-scope="scope">
                        <el-row>
                          <el-col :span="8">
                            <el-progress :percentage="parseFloat(scope.row.diskPercent>100?100:scope.row.diskPercent)" :show-text="false" :stroke-width="10" color="#60DD88" style="width: 60px;margin: auto;display:inline-block;"></el-progress>
                          </el-col>
                          <el-col :span="10">
                            <div style="display:inline-block;">{{scope.row.disk}}</div>
                          </el-col>
                        </el-row>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-row>
              </el-card>

              <el-card style="width:95%;margin:10px;" v-loading="loadingInformation">
                <el-row>
                  <el-col :span="1"><div style="width: 4px;height: 17px;background-color: #409EFF"></div></el-col>
                  <el-col :span="3" style="line-height: 17px">实例</el-col>
                </el-row>
                <el-row style="background-color: #F5F5F5;font-size: 12.5px;text-align: center;font-weight: bold;height: 26px;line-height: 26px;margin-top:10px">
                  <el-col :span="8">角色名称</el-col>
                  <el-col :span="8">状态</el-col>
                  <el-col :span="8">日志</el-col>
                </el-row>
                <el-row class="example" style="font-size: 15px;text-align: center" v-show="essentialInformation.logFileQO.nodeType != null">
                  <el-col :span="8" style="margin-top: 10px;">
                    <router-link style="text-decoration: none;color: #409EFF;" :to="{path:'/node-detail',query:{clusterId:essentialInformation.logFileQO.id,hostId:this.hostId}}">{{essentialInformation.logFileQO.nodeType}}</router-link>
                  </el-col>
                  <el-col :span="8">
                    <div v-if="essentialInformation.state == 'ACTIVE'" style="margin-top: 10px;">
                      <div style="width: 8px;height: 8px;background-color: #5EDD86;border-radius: 50%;display:inline-block"></div>
                      <div style="display:inline-block">{{runStates[0].label}}</div>
                    </div>
                    <div v-else style="margin-top: 10px;" class="status">
                      <div style="width: 8px;height: 8px;background-color: red;border-radius: 50%;display:inline-block"></div>
                      <div style="display:inline-block">{{runStates[2].label}}</div>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <el-select class="border" v-model="logFilePathsVal" clearable placeholder="选择日志"  @change="selectLogFile">
                      <el-option
                        v-for="(item,index) in essentialInformation.logFileQO.logFilePaths"
                        :key="index"
                        :label="item"
                        :value="item"
                      >
                      </el-option>
                    </el-select>
                  </el-col>
                </el-row>
              </el-card>
            </div>

            <div style="width:75%;display:flex;flex-direction:row;flex-wrap:wrap;">

              <el-card style="width:47.5%;height:367px;margin:10px;" v-show="showCpu" v-loading="loadingInformation">
                <el-row>
                  <el-col :span="1">
                    <div style="width: 4px;height: 17px;background-color: #409EFF;"></div>
                  </el-col>
                  <el-col :span="8" style="line-height: 17px">主机CPU使用率</el-col>
                </el-row>
                <el-row>
                  <div style="width: 100%;height: 350px" id="cpuUtilization"></div>
                </el-row>
              </el-card>

              <el-card style="width:47.5%;height:367px;margin:10px;" v-show="showMemory" v-loading="loadingInformation">
                <el-row>
                  <el-col :span="1">
                    <div style="width: 4px;height: 17px;background-color: #409EFF;"></div>
                  </el-col>
                  <el-col :span="5" style="line-height: 17px">主机内存使用率</el-col>
                </el-row>
                <el-row>
                  <div style="width:100%;height:350px;" id="memoryUsage"></div>
                </el-row>
              </el-card>

              <el-card style="width:47.5%;height:367px;margin:10px;" v-show="showDisk" v-loading="loadingInformation">
                <el-row>
                  <el-col :span="1">
                    <div style="width: 4px;height: 17px;background-color: #409EFF;"></div>
                  </el-col>
                  <el-col :span="5" style="line-height: 17px">主机磁盘使用率</el-col>
                </el-row>
                <el-row>
                  <div style="width: 100%;height: 350px" id="diskUtilization"></div>
                </el-row>
              </el-card>

              <el-card style="width:47.5%;height:367px;margin:10px;" v-show="showNetRate" v-loading="loadingInformation">
                <el-row>
                  <el-col :span="1">
                    <div style="width: 4px;height: 17px;background-color: #409EFF;"></div>
                  </el-col>
                  <el-col :span="5" style="line-height: 17px">主机带宽使用率</el-col>
                </el-row>
                <el-row>
                  <div style="width: 100%;height: 350px" id="netRate"></div>
                </el-row>
              </el-card>

            </div>
          </div>
        </el-tab-pane>
        <div>
          <el-dialog :visible.sync="dialogVisible" v-model="dialogVisible" title="提示" width="540px" @closed="closeDelDia">
            <span>确认删除此主机?</span>
            <template #footer>
              <div class="adv_del">
                <el-button @click="dialogVisible = false,value = ''">取消</el-button>
                <el-button type="primary" @click="delEcs">确认</el-button>
              </div>
            </template>
          </el-dialog>
        </div>
      </el-tabs>
    </el-row>
  </el-row>
</template>
<script>
import {doGet, doPost} from '@/api/index.js'
import clusterlist from '@/view/cluster/list'
import * as echarts from 'echarts'
import '../../css/style.css'

export default {
  components: {
    'clusterlist': clusterlist
  },
  data () {
    return {
      serverUsl: `${process.env.BASE_API}`,
      dialogVisible: false,
      diskList: [
        {
          'diskName': '虚拟磁盘',
          'mountPoint': 33,
          'diskUsage': 20,
          'diskCapacity': '2G/10G'
        }
      ],
      disk: {
        time: [],
        percentage: []
      },
      memory: {
        time: [],
        percentage: []
      },
      cpu: {
        time: [],
        percentage: []
      },
      runStates: [{
        value: 'ACTIVE',
        label: '运行中'
      }, {
        value: 'INACTIVE',
        label: '空闲'
      }, {
        value: 'SHUTTING_DOWN',
        label: '停止'
      }],
      // basic information
      essentialInformation: {
        'name': '- -',
        'ip': '- -',
        'serviceIp': '- -',
        'memory': '- -',
        'cpu': '- -',
        'state': '- -',
        'java': '- -',
        'py': '- -',
        'ssh': '- -',
        'disks': [],
        'logFileQO': {
          'id': '',
          'nodeType': '',
          'state': '',
          'logFilePaths': []
        }

      },
      logFilePathsVal: '',
      select: [{
        value: 'del',
        label: '删除'
      }],
      selectTimeData: [{
        value: '0',
        label: '实时'
      }, {
        value: '1',
        label: '1小时'
      }, {
        value: '2',
        label: '2小时'
      }, {
        value: '3',
        label: '6小时'
      }, {
        value: '4',
        label: '12小时'
      }, {
        value: '5',
        label: '1天'
      }, {
        value: '6',
        label: '1周'
      }, {
        value: '7',
        label: '1月'
      }],
      time: '0',
      chart: [],
      value: '',
      selectChartData: [{
        value: 'cpu',
        label: '主机CPU使用率'
      }, {
        value: 'memory',
        label: '主机内存使用率'
      }, {
        value: 'disk',
        label: '主机磁盘使用率'
      },{
        value: 'netRate',
        label: '主机带宽使用率'
      }],
      title: {
        manageIp: '1',
        serviceIp: '2',
        ram: '3',
        totalRam: '4',
        cpu: '5',
        totalCpu: '6',
        clusterNum: '7',
        totalClusterNum: '8'
      },
      hostId: '',
      defaultActivityName: 'first',
      CarbonDataName: 'CarbonData',
      currentConfigType: 'ClickHouse',
      activeName: 'second',
      tabPosition: 'left',
      data: {
        'common': {
          'common1': {
            'join-distribution-type': 'AUTOMATIC',
            'redistribute-writes': true
          }
        },
        'jvm': {
          'jvm1': {
            'jvm': '22222222222'
          }
        },
        'ClickHouse': {
          ClickHouseTabsValue: '1',
          clickHouseTabIndex: 2,
          ClickHouseTabs: [
            {
              title: '连接器1',
              name: '1',
              configGroup: '1'
            }
          ],

          'ClickHouse1': {
            'connector.name': 'clickhouse',
            'connection-url': 'jdbc:clickhouse0://example.net:8123',
            'connection-user': 'username',
            'connection-password': 'yourpassword',
            'allow-drop-table': true
          },

          'ClickHouse2': {
            'connector.name': 'clickhouse',
            'connection-url': 'jdbc:clickhouse1://example.net:8123',
            'connection-user': 'username',
            'connection-password': 'yourpassword',
            'allow-drop-table': true
          }
        }
      },
      loadingInformation:true,
      clock:null,
      cpuEcharts:null,
      memoryEcharts:null,
      diskUtilizationEcharts:null,
      netRateEcharts:null,
      cpuResultList:[],
      memoryResultList:[],
      diskResultList:[],
      netRateResultList:[]
    }
  },
  created () {
    this.hostId = this.$route.query.hostId;
  },
  mounted () {
    let that=this;
    this.bgColor();
    this.getOne();

    this.cpuEcharts = echarts.init(document.getElementById('cpuUtilization'), null)
    this.memoryEcharts = echarts.init(document.getElementById('memoryUsage'), null)
    this.diskUtilizationEcharts = echarts.init(document.getElementById('diskUtilization'), null)
    this.netRateEcharts = echarts.init(document.getElementById('netRate'), null)
    this.clock=setInterval(function()
    {
      that.getOneInterval();
      that.getEchartsData();
    },1000)
  },
  beforeDestroy()
  {
    clearInterval(this.clock)
    this.clock=null
  },
  methods: {
    closeDelDia () {},
    selectLogFile (val) {
      this.downloadFile(val)
    },
    downloadFile (val) {
      let that=this;
      let url = '/sys_ecs/downloadFile'
      let obj = {
        'ecsId': this.hostId,
        'fileName': val
      }
      doPost(url, obj).then(res => {
        this.logFilePathsVal='';
        if (res.data.code == 0)
        {
          let baseApi=`${process.env.UPLOAD_PARAM}` + res.data.data;
          that.downloadRes(val,baseApi)
        }
        else
        {
          this.$message.error("下载失败")
        }
      })
    },
    async downloadRes(name,url){
      let response = await fetch(url); // change content as blob address
      let blob = await response.blob();  // create hidden download link
      let objectUrl = window.URL.createObjectURL(blob);
      let a = document.createElement('a');
      a.href = objectUrl;
      a.download = name;
      a.click()
      a.remove();
    },
    bgColor () {
      document.body.style.backgroundColor = '#F9F9F9 '
    },
    getOne () {
      let url = '/sys_ecs/one'
      let obj = {'id': this.hostId}
      doGet(url, obj).then(res => {
        if (res.data.code === 0) {
          this.essentialInformation = res.data.data
          this.loadingInformation=false;
        }
      })
    },
    getOneInterval () {
      let url = '/sys_ecs/one'
      let obj = {'id': this.hostId}
      doGet(url, obj).then(res => {
        if (res.data.code === 0) {
          this.essentialInformation.memory = res.data.data.memory;
          this.essentialInformation.cpu = res.data.data.cpu;
          this.essentialInformation.state = res.data.data.state;
        }
      })
    },
    delEcs () {
      let url = '/sys_ecs/delete'
      var hostIps = []
      hostIps.push(this.hostId)
      doPost(url, hostIps).then(res => {
        if (res.data.code === 0) {
          this.dialogVisible = false
          this.$message.success(res.data.msg)
          // this.queryEcs({});
        }
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.$router.go(-1)
        }, 2000)
      })
    },

    initDiskUtilization (echartData) {
      let that=this;
      let option =
      {
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          boundaryGap:false,
          axisLabel:
          {
            interval:1,
            formatter:function(value)
            {
              return value.slice(0,11)+"\n"+value.slice(11)
            }
          },
          splitLine: {
            show: false
          }
        },
        yAxis: {
          name:'(单位%)',
          type: 'value',
          max:100
        },
        series: [
          {
            data:echartData,
            type: 'line',
            showSymbol: false,
          }
        ]
      }
      new Promise((resolve)=>{resolve();}).then(()=>
      {
        that.diskUtilizationEcharts.setOption(option)
      })
    },
    initMemoryUsage (echartData) {
      let that=this;
      let option =
      {
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          boundaryGap:false,
          axisLabel:
          {
            interval:1,
            formatter:function(value)
            {
              return value.slice(0,11)+"\n"+value.slice(11)
            }
          },
          splitLine: {
            show: false
          }
        },
        yAxis: {
          name:'(单位%)',
          type: 'value',
          max:100
        },
        series: [
          {
            data:echartData,
            type: 'line',
            showSymbol: false,
          }
        ]
      }
      new Promise((resolve)=>{resolve();}).then(()=>{
        that.memoryEcharts.setOption(option)
      })
    },
    initCpuUtilization (echartData)
    {
      let that=this;
      let option =
      {
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          boundaryGap:false,
          axisLabel:
          {
            interval:1,
            formatter:function(value)
            {
              return value.slice(0,11)+"\n"+value.slice(11)
            }
          },
          splitLine: {
            show: false
          }
        },
        yAxis: {
          name:'(单位%)',
          type: 'value',
          max:100
        },
        series: [
          {
            data:echartData,
            type: 'line',
            showSymbol: false,
          }
        ]
      }
      new Promise((resolve)=>{resolve();}).then(()=>{
        that.cpuEcharts.setOption(option)
      })

    },
    initNetRate (echartData)
    {
      let that=this;
      let option =
      {
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          boundaryGap:false,
          axisLabel:
          {
            interval:1,
            formatter:function(value)
            {
              return value.slice(0,11)+"\n"+value.slice(11)
            }
          },
          splitLine: {
            show: false
          }
        },
        yAxis: {
          name:'kb/s',
          type: 'value',
        },
        series: [
          {
            data:echartData,
            type: 'line',
            showSymbol: false,
          }
        ]
      }
      new Promise((resolve)=>{resolve();}).then(()=>{
        that.netRateEcharts.setOption(option)
      })

    },
    getEchartsData()
    {
      this.cpuResultList=[];
      this.diskResultList=[];
      this.memoryResultList=[];
      this.netRateResultList=[];
      let that = this;
      let url = "/sys_ecs/getHostItem";
      let obj =
      {
        ecsId:this.hostId,
        queryType:this.time
      }
      doGet(url, obj).then(res =>
      {
        if(res.data.code==0)
        {
          that.initCpuUtilization(that.formatEchartsData(that.cpuResultList,res.data.data.cpu));
          that.initDiskUtilization(that.formatEchartsData(that.diskResultList,res.data.data.disk));
          that.initMemoryUsage(that.formatEchartsData(that.memoryResultList,res.data.data.ram));
          that.initNetRate(that.formatEchartsData(that.netRateResultList,res.data.data.netRate))
        }
      })
    },
    formatEchartsData(list,obj)
    {
      if(list.length==0)
      {
        for(let key in obj)
        {
          list.push([key,obj[key]])
        }
      }
      else
      {
        list.splice(0,1);
        let arr=Object.keys(obj);
        let key=arr[arr.length-1];
        list.push([key,obj[key]])
      }
      return list
    },

    selectTime (e) {},
    selectChart (e) {},
    operation (e) {
      if (e == 'del') {
        this.dialogVisible = true
      }
    },

    getClusterConfig () {
      let apiUrl = '/sys_openlookeng_cluster_config/getClusterConfig'
      let param = {'clusterCode': 'yuelianwgan'}
      let _this = this
      doGet(apiUrl, param).then((response) => {
        // debugger
        _this.data = response.data.data
      })
    },

    handleClick (tab, event) {
      this.currentConfigType = tab.name
      console.log('切换了:' + tab.name)
    },
    handleTabsEdit (targetName, action) {
      let configType = this.currentConfigType
      let tabsArrayName = configType + 'Tabs'
      let tabsValName = configType + 'TabsValue'
      let tabsIndexName = configType + 'TabIndex'
      if (action === 'add') {
        let newTabName = ++this.data[configType][tabsIndexName] + ''
        let configGroup = configType + newTabName
        let obj = {
          title: '连接器' + newTabName,
          name: newTabName,
          configGroup: this.data[configType][tabsIndexName]
        }
        this.data[configType][tabsArrayName].push(obj)
        this.data[configType][tabsValName] = newTabName
        this.data[configType][configGroup] = {}
      }
      if (action === 'remove') {
        let tabs = this.data[configType][tabsArrayName]
        if (tabs.length == 1) {
          this.$message.error('请保留至少一个配置!')
          return false
        }
        let activeName = this.data[configType][tabsValName]
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1]
              if (nextTab) {
                activeName = nextTab.name
              }
            }
          })
        }
        this.data[configType][tabsValName] = activeName
        this.data[configType][tabsArrayName] = tabs.filter(tab => tab.name !== targetName)
      }
    }

  },
  computed:
  {
    showCpu() {
      return this.chart.length == 0 || this.chart.indexOf("cpu") !== -1
    },
    showMemory() {
      return this.chart.length == 0 || this.chart.indexOf("memory") !== -1
    },
    showDisk() {
      return this.chart.length == 0 || this.chart.indexOf("disk") !== -1
    },
    showNetRate() {
      return this.chart.length == 0 || this.chart.indexOf("netRate") !== -1
    },
  },
}
</script>
<style>

  .border{
    margin-left: -40px;
    position:absolute;
    clip:rect(2px 90px 30px 2px);
    width:140px;
    /*height:28px;*/
    /*line-height:28px;*/
    font-size:15px;
    font-weight:bold;
    color: #409EFF;
  }
  .color{
    color: #999999;
  }
  .row{
    height: 28px;
    margin-top: 5px;
    line-height: 28px;
    font-size: 13px;
  }
  .font{
    font-size: 13px;
    line-height: 28px;
  }
  .breadcrumbColor /deep/ .el-breadcrumb__inner {
    color: #B9B9B9;
  }
</style>
<style scoped>
  .example{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    width: 100%;
  }
</style>
